var _ = require('lodash'),
    Q = require('q'),
    PublicEnum = require('../../../Base/server/controllers/Enum'),
    ProduceWorkEnum = require('./Enum.server.controller.js'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    kanbanDemandController = require('./KanbanDemand.server.controller.js');

// 转接区入库：写入库记录
// barcodeMasters: 入库物料信息，包含以下字段：
//      BarcodeMaster、Barcode、ItemMaster、DescSeg1、DescSeg2、BusinessDocID、RcvUser、RcvOperation、BizRecord、WareHouse、RcvDateTime(可无，默认为当前时间)
exports.addStockQty = function (barcodeMasters) {
    var deferred = Q.defer();

    var rcvRecords = [];
    _.forEach(barcodeMasters, function (barcodeMaster) {
        _.merge(barcodeMaster, {
            RowStatus: PublicEnum.RowStatus.Insert,
            CreatedBy: barcodeMaster.RcvUser,
            RcvBusinessType: ProduceWorkEnum.RcvBusinessType.WareHouse,
            RcvQty: 1
        });
        rcvRecords.push(barcodeMaster);
    });
    var entity = entityCollection.getEntity("RcvRecord");
    entity.save(rcvRecords, function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '新增错误';
            newErr.message = '新增入库记录错误，请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(records);
    });

    return deferred.promise;
};
//查询出入库记录，工单信息
exports.queryRcvRecords = function (completeFun) {
    var rcvRecordEntity = entityCollection.getEntity("RcvRecord");
    var gtDate = new Date();
    gtDate.setHours(0);
    gtDate.setMinutes(0);
    gtDate.setSeconds(0);
    gtDate.setMilliseconds(0);

    var gtDateCopy = new Date();
    gtDateCopy.setHours(0);
    gtDateCopy.setMinutes(0);
    gtDateCopy.setSeconds(0);
    var Milliseconds = 24 * 60 * 60 * 1000;
    var ltDate = new Date(gtDateCopy.setMilliseconds(0) + Milliseconds);
    rcvRecordEntity.find({
            RcvBusinessType: 0,
            RcvDateTime: {$gte: gtDate, $lt: ltDate}
        },
        null, [{
            path: "BarcodeMaster",
            select: "ShipLotNumber MOLotNumber MO",
            populate: [{
                path: "MO",
                select: "Customer",
                model: 'MO'
            }]
        }],
        function (err, records) {
            if (err) {
                completeFun(err);

            } else {
                var recordObj = {};
                _.forEach(records, function (record) {
                    if (record.BarcodeMaster && !recordObj[record.BarcodeMaster.MOLotNumber]) {
                        recordObj[record.BarcodeMaster.MOLotNumber] = {
                            ShipLotNumber: record.BarcodeMaster.ShipLotNumber ? record.BarcodeMaster.ShipLotNumber : "",
                            MOLotNumber: record.BarcodeMaster.MOLotNumber ? record.BarcodeMaster.MOLotNumber : "",
                            Customer: record.BarcodeMaster.MO ? record.BarcodeMaster.MO.Customer : "",
                            Count: 0
                        };
                    }
                    if (record.BarcodeMaster && recordObj[record.BarcodeMaster.MOLotNumber]) {
                        recordObj[record.BarcodeMaster.MOLotNumber].Count += 1;
                    }
                });
                var recordArr = [];
                for (var item in recordObj) {
                    recordArr.push(recordObj[item]);
                }
                recordArr.sort(ArraySortByKey("MOLotNumber"));
                completeFun(null, recordArr);
            }
        });
};

//根据条码主档查询入库记录
exports.queryRcvRecordsByBarcodeMaster = function (barcodeMaster, completeFun) {
    var entity = entityCollection.getEntity("RcvRecord");
    entity.findOne({BarcodeMaster: barcodeMaster}, null, function (err, record) {
        if (err) {
            completeFun(err);
        } else {
            completeFun(null, record);
        }
    });
};

//批量查询入库记录
exports.queryByCondition = function (condition, completeFun) {
    var entity = entityCollection.getEntity("RcvRecord");
    entity.find(condition, null, null, function (err, records) {
        if (err) {
            completeFun(err);
        } else {
            completeFun(null, records);
        }
    });
};

// 从“入库记录表”中获取“货架ID=空”的相应待转区ID的记录
exports.queryByContainerAndWareHouse = function (WareHouseId, completeFun) {
    var entity = entityCollection.getEntity("RcvRecord");
    // entity.find({WareHouse: WareHouseId,Container: null}, null, [{
    entity.find({WareHouse: WareHouseId}, null, [{
        path: 'BarcodeMaster',
        select: 'ItemMaster ItemMasterCode DescSeg1 DescSeg2'
    }], function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询入库记录错误';
            newErr.message = '请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};
//通过货架查找入库记录
exports.queryByContainer = function (ContainerId, completeFun) {
    var entity = entityCollection.getEntity("RcvRecord");
    entity.find({Container: ContainerId}, null, null, function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询入库记录错误';
            newErr.message = '请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};

// 根据物料查找已备货量
exports.queryStockQty = function (itemMasterId, completeFun) {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("RcvRecord");
    entity.Entity.find({
        ItemMaster: itemMasterId, 
        Container: { $ne: null }
    }).count().exec(function (err, stockQty) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询入库记录错误';
            newErr.message = '查询入库记录错误, 请检查查询参数！';
            deferred.reject(newErr);
        } else {
            deferred.resolve(stockQty);
        }
    });

    return deferred.promise;
};

//数组排序
function ArraySortByKey(key) {
    return function (objFirst, objSecond) {
        var aStr, bStr;
        if (typeof objFirst === "object" && typeof objSecond === "object" && objFirst && objSecond) {
            aStr = objFirst[key];
            bStr = objSecond[key];
            if (aStr === bStr) {
                return 0;
            }
            if (typeof aStr === typeof bStr) {
                return aStr < bStr ? -1 : 1;
            }
            return typeof aStr < typeof bStr ? -1 : 1;
        } else {
            throw ("error");
        }
    }
}

function createKanbanDemand(itemMaster, descSeg1, descSeg2, wareHouseId) {
    var deferred = Q.defer();

    kanbanDemandController.findOne({
        ItemMaster: itemMaster,
        DescSeg1: descSeg1,
        DescSeg2: descSeg2
    }, wareHouseId).then(function (record) {
        if (!record) {
            return kanbanDemandController.insert({
                ItemMaster: itemMaster,
                DescSeg1: descSeg1,
                DescSeg2: descSeg2,
                WareHouse: wareHouseId,
                TotalDemandQty: 0,
                TotalStockQty: 0,
                TotalReceiveQty: 0
            });
        } else {
            return Q.resolve(record);
        }
    }).then(function (record) {
        deferred.resolve(record);
    }).catch(function (err) {
        deferred.reject(err);
    })
        .done();

    return deferred.promise;
}
